//
//  NutritionAndHealthViewController.swift
//  YLH
//
//  Created by qinjiangtao on 2024/1/20.
//  营养健康页面

import UIKit
import Alamofire

class NutritionAndHealthViewController: UIViewController, UITextFieldDelegate {
    
    var listModel = HomeListModel()
    private var scrollView = UIScrollView()
    private var imgBtn = UIButton()
    private var selectImg = UIImage()
    /// 重量
    private var weightTextF = UITextField()
    /// 容量
    private var capacityTextF = UITextField()
    /// 大小
    private var sizeTextF = UITextField()
    private var searchTextF = UITextField()
    private var titleL8 = UILabel()
    private var model = NutritionAndHealthModel()
    private var foodList = [FoodModel]()
    private var selectFoodID = ""
    
    private var leftTitleArr = [String]()
    private var centerTitleArr = [String]()
    private var rightTitleArr = [String]()
    private var percentageTitleArr = [String]()
    
    var grids = [[Grid]]()
    let tabulationView = TabulationView()
    let reuseIdentifier = "text"
    
    /// 行数
    let rowCount = 19
    /// 列数
    let colCount = 4
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "营养健康"
        leftTitleArr = ["能量(千卡)", "蛋白质(克)", "碳水化合物(克)", "脂肪(克)", "膳食纤维(克)", "糖(克)", "饱和脂肪(克)", "反式脂肪(克)", "胆固醇(毫克)", "钙(毫克)", "铜(毫克)", "铁(毫克)", "镁(毫克)", "锰(毫克)", "磷(毫克)", "钾(毫克)", "钠(毫克)", "锌(毫克)", "维生素C(毫克)"]
        centerTitleArr = ["Energy(kcal)", "Protein(g)", "Carbohydrates(g)", "Fat(g)", "Dietary Fiber(g)", "Sugar(g)", "Saturated fat(g)", "Trans fat(g)", "Cholesterol(mg)", "Calcium(mg)", "Copper (mg)", "lron(mg)", "Magnesium (mg)", "Manganese（mg)", "Phosphorus（mg)", "Potassium（mg)","Sodium（mg)", "Zinc（mg)", "Vitamin Cha(mg)"]
        
//        selectImg = UIImage(named: "shaoji") ?? UIImage()
        addUI()
        generateData()
        
        
    }
    
    private func addUI() {
        self.view.addGradientColor(fromColors: [ColorWithStr("#FFB2B5").cgColor, ColorWithStr("#FCDFE0").cgColor, ColorWithStr("#FFFBFB").cgColor], locationArr: [0, 0.5, 1.0], with: .topToBottom)
        
        scrollView = UIScrollView(frame: CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - NAV_HEIGHT))
        scrollView.contentSize = CGSize(width: SCREEN_WIDTH, height: SCREEN_HEIGHT * 2 + 70)
        view.addSubview(scrollView)
        
        // HTML字符串
        let htmlString = "\(listModel.explain)"//"<p>hello</p>"//
        guard let data = htmlString.data(using: .utf8) else {
            ShowHUD(str: "富文本解析失败")
            return
        }
        print(htmlString)
        let size = listModel.explain.tt_size(with: SYSFONT(ofSize: 15), constrainedToWidth: SCREEN_WIDTH - 30)
        let explainL = YYLabel().then({
            $0.frame = CGRect(x: 15, y: 15, width: SCREEN_WIDTH - 30, height: size.height + 20)
            $0.backgroundColor = .clear
            $0.text = "\(listModel.explain)"
            $0.textContainerInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
            $0.numberOfLines = 0
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 15)
            $0.addRoundedCorners(withRadius: 10)
        })
        scrollView.addSubview(explainL)
        
        if let attributedString = try? NSMutableAttributedString(data: data, options: [.documentType : NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) {
            explainL.attributedText = attributedString
            let height = attributedString.boundingRect(with: CGSize(width: SCREEN_WIDTH - 30, height: CGFloat(MAXFLOAT)), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).height
//            let size = attributedString.size()
            explainL.height = height
        } else {
            print("无效的HTML字符串")
        }
        
        
        let imgBgView = UIView()
        imgBgView.frame = CGRect(x: 15, y: explainL.bottom + 15, width: SCREEN_WIDTH - 30, height: 222)
        imgBgView.backgroundColor = .clear
        imgBgView.addRoundedCorners(withRadius: 10)
        scrollView.addSubview(imgBgView)
        
        imgBtn = UIButton().then {
            $0.frame = CGRect(x: imgBgView.width / 2 - 75, y: 20, width: 150, height: 150)
            $0.setImage(UIImage(named: "noo"), for: .normal)
            $0.imageView?.contentMode = .scaleAspectFill
            $0.addRoundedCorners(withRadius: 8)
//            $0.addTarget(self, action: #selector(imgBtnClick), for: .touchUpInside)
        }
        imgBgView.addSubview(imgBtn)
        
        let titleL1 = UILabel().then({
            $0.frame = CGRect(x: 0, y: imgBtn.bottom + 15, width: imgBgView.width, height: 18)
            $0.text = "请上传图片"
            $0.textAlignment = .center
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 13)
        })
        imgBgView.addSubview(titleL1)
        
        let photoBtn = UIButton().then {
            $0.frame = CGRect(x: 15, y: imgBgView.bottom + 20, width: SCREEN_WIDTH / 2 - 25, height: 45)
            $0.backgroundColor = ColorWithStr("#FFE4E7")
            $0.titleLabel?.font = SYSFONT(ofSize: 13)
            $0.setTitle("选择图片/手机拍摄", for: .normal)
            $0.setTitleColor(MainColor, for: .normal)
            $0.addRoundedCorners(withRadius: 8)
            $0.addBorder(withWidth: 1, borderColor: MainColor)
            $0.addTarget(self, action: #selector(photoBtnClick), for: .touchUpInside)
        }
        scrollView.addSubview(photoBtn)
        
        let uploadBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH / 2 + 10, y: photoBtn.top, width: photoBtn.width, height: photoBtn.height)
            $0.backgroundColor = MainColor
            $0.titleLabel?.font = SYSFONT(ofSize: 13)
            $0.setTitle("上传", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 8)
            $0.addTarget(self, action: #selector(uploadBtnClick), for: .touchUpInside)
        }
        scrollView.addSubview(uploadBtn)
        
        let titleL2 = UILabel().then({
            $0.frame = CGRect(x: 0, y: photoBtn.bottom + 25, width: SCREEN_WIDTH, height: 22)
            $0.text = "请选择菜单"
            $0.textAlignment = .center
            $0.textColor = Color333333
            $0.font = SYSFONTBOLD(ofSize: 16)
        })
        scrollView.addSubview(titleL2)
        
        collectionView.frame = CGRect(x: 0, y: titleL2.bottom + 20, width: SCREEN_WIDTH, height: 70)
        scrollView.addSubview(collectionView)
        
        let titleL3 = UILabel().then({
            $0.frame = CGRect(x: 0, y: collectionView.bottom + 25, width: SCREEN_WIDTH, height: 22)
            $0.text = "名称搜索"
            $0.textAlignment = .center
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 16)
        })
        scrollView.addSubview(titleL3)
        
        let leftView = UIView()
        leftView.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
        let searchImgView = UIImageView().then {
            $0.frame = CGRect(x: 10, y: 10, width: 14, height: 14)
            $0.image = UIImage(named: "首页搜索")
            $0.contentMode = .scaleAspectFill
        }
        leftView.addSubview(searchImgView)
        searchTextF = UITextField().then {
            $0.frame = CGRect(x: 35, y: titleL3.bottom + 15, width: SCREEN_WIDTH - 70, height: 34)
            $0.font = SYSFONT(ofSize: 12)
            $0.placeholder = "请输入搜索内容"
            $0.backgroundColor = ColorEEEEEE
            $0.returnKeyType = .search
            $0.delegate = self
            $0.leftView = leftView
            $0.leftViewMode = .always
            $0.addRoundedCorners(withRadius: 17)
        }
        scrollView.addSubview(searchTextF)
        
        let titleL4 = UILabel().then({
            $0.frame = CGRect(x: 0, y: searchTextF.bottom + 15, width: SCREEN_WIDTH, height: 22)
            $0.text = "营养列表"
            $0.textAlignment = .center
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 16)
        })
        scrollView.addSubview(titleL4)
        
        addSetingView()
        
        let cellW = (SCREEN_WIDTH - 30) / 3
        let titleL6 = UILabel().then({
            $0.frame = CGRect(x: 15, y: sizeTextF.bottom + 20, width: cellW, height: 40)
            $0.backgroundColor = MainColor
            $0.text = "营养资料"
            $0.textAlignment = .center
            $0.textColor = .white
            $0.font = SYSFONTBOLD(ofSize: 15)
        })
        scrollView.addSubview(titleL6)
        let titleL7 = UILabel().then({
            $0.frame = CGRect(x: titleL6.right, y: sizeTextF.bottom + 20, width: cellW, height: 40)
            $0.backgroundColor = MainColor
//            $0.text = "Name"
            $0.textAlignment = .center
            $0.textColor = .white
            $0.font = SYSFONTBOLD(ofSize: 15)
        })
        scrollView.addSubview(titleL7)
        titleL8 = UILabel().then({
//            $0.frame = CGRect(x: titleL7.right, y: sizeTextF.bottom + 20, width: cellW / 2, height: 40)
            $0.frame = CGRect(x: titleL6.right, y: sizeTextF.bottom + 20, width: cellW * 2, height: 40)
            $0.backgroundColor = MainColor
            $0.text = ""
            $0.textAlignment = .center
            $0.textColor = .white
            $0.font = SYSFONTBOLD(ofSize: 15)
        })
        scrollView.addSubview(titleL8)
        
        let titleL9 = UILabel().then({
            $0.frame = CGRect(x: titleL8.right, y: sizeTextF.bottom + 20, width: cellW / 2, height: 40)
            $0.backgroundColor = MainColor
//            $0.text = "百分比"
            $0.textAlignment = .center
            $0.textColor = .white
            $0.font = SYSFONTBOLD(ofSize: 15)
        })
//        scrollView.addSubview(titleL9)
        
        addMianRongJianKangUI()
    }
    
    private func addSetingView() {
        
        let titleArr = ["食物重量(克)", "食物容量(毫升)", "食物手掌大小"]
        var minX = searchTextF.bottom + 52
        for (index, titleStr) in titleArr.enumerated() {
            let titleL5 = UILabel().then({
                $0.frame = CGRect(x: 30, y: minX, width: 100, height: 34)
                $0.text = titleStr//"食物总重量(克）"
                $0.textAlignment = .right
                $0.textColor = Color333333
                $0.font = SYSFONT(ofSize: 12)
            })
            scrollView.addSubview(titleL5)
            
            let leftView1 = UIView()
            leftView1.frame = CGRect(x: 0, y: 0, width: 10, height: 0)
            let TextF = UITextField().then {
                $0.frame = CGRect(x: titleL5.right + 10, y: titleL5.top, width: SCREEN_WIDTH - 250, height: 34)
                $0.font = SYSFONT(ofSize: 14)
                $0.placeholder = ""
                $0.text = ""
                $0.delegate = self
                $0.keyboardType = .numberPad
                $0.backgroundColor = ColorEEEEEE
                $0.leftView = leftView1
                $0.leftViewMode = .always
                $0.addRoundedCorners(withRadius: 5)
            }
            scrollView.addSubview(TextF)
            
            if index == 0 {
                weightTextF = TextF
                weightTextF.text = ""
            } else if index == 1 {
                capacityTextF = TextF
            } else if index == 2 {
                sizeTextF = TextF
            }
            
            let setBtn = UIButton().then {
                $0.frame = CGRect(x: SCREEN_WIDTH - 100, y: titleL5.top, width: 66, height: 34)
                $0.backgroundColor = MainColor
                $0.tag = index + 1
                $0.titleLabel?.font = SYSFONT(ofSize: 13)
                $0.setTitle("设置", for: .normal)
                $0.setTitleColor(.white, for: .normal)
                $0.addRoundedCorners(withRadius: 5)
                $0.addTarget(self, action: #selector(setBtnClick(btn:)), for: .touchUpInside)
            }
            scrollView.addSubview(setBtn)
            
            minX = titleL5.bottom + 10
        }
    }
    
    
    /// 设置食物克数
    @objc private func setBtnClick(btn: UIButton) {
        let weightStr = weightTextF.text ?? ""
        let capacityStr = capacityTextF.text ?? ""
        let palm_sizeStr = sizeTextF.text ?? ""
        let param = [
            "id": selectFoodID,
            "type": "\(btn.tag)",     //1：重量 2：容量 3：手掌大小
            "weight": weightStr,
            "capacity": capacityStr,
            "palm_size": palm_sizeStr
        ]
        QINetworkManager.requestJson(urlStr: "/Check/healthNutrition", parameters: param) { json in
//            print(json)
            let result = json["result"]
            self.setRightTitleArr(json: result)
        }
    }
    /// 搜索食物
    private func searchFoodData() {
        let searchStr = searchTextF.text ?? ""
        //"health_id": model.health_id, 
        QINetworkManager.requestJson(urlStr: "/Check/healthSearch", method: .get, parameters: ["keyword":searchStr], success: { json in
            print(json)
            self.foodList.removeAll()
            let modeArr = json.arrayObject?.kj.modelArray(FoodModel.self) ?? [FoodModel]()
            self.foodList = modeArr
            self.collectionView.reloadData()
        })
        
    }
    
    @objc private func photoBtnClick() {
        let alertCtl = UIAlertController(title: "选项", message: nil, preferredStyle: .actionSheet)
        alertCtl.addAction(UIAlertAction(title: "拍照", style: .default, handler: { (_) in
            let imagePickerCtl = UIImagePickerController()
            imagePickerCtl.delegate = self
            imagePickerCtl.allowsEditing = true
            imagePickerCtl.sourceType = .camera
            self.present(imagePickerCtl, animated: true)
        }))
        alertCtl.addAction(UIAlertAction(title: "从手机相册选择", style: .default, handler: { (_) in
            let imagePickerCtl = UIImagePickerController()
            imagePickerCtl.delegate = self
            imagePickerCtl.allowsEditing = true
            imagePickerCtl.sourceType = .savedPhotosAlbum
            self.present(imagePickerCtl, animated: true)
        }))
        alertCtl.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
            
        }))
        self.present(alertCtl, animated: true)
    }
    
    @objc private func uploadBtnClick() {
        updateImage()
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        searchFoodData()
        return true
    }
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
//        guard model.list.count > 0 else {
//            ShowHUD(str: "请上传图片")
//            return false
//        }
        if textField == searchTextF {
            let searchView = SearchListView(frame: CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
            searchView.model = model
            searchView.selectModel = { model in
                self.getHealthConfirm(model: model)
            }
            QINPopUpTool.sharedInstance().popUp(with: searchView, withAnimation: .none, withCanTapBgCancel: true, closeBefore: .hidden, bgColor: .clear)
            return false
        } else if textField == weightTextF {
            capacityTextF.text = ""
            sizeTextF.text = ""
        } else if textField == capacityTextF {
            weightTextF.text = ""
            sizeTextF.text = ""
        } else if textField == sizeTextF {
            capacityTextF.text = ""
            weightTextF.text = ""
        }
        return true
    }

    lazy var collectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = 10
        flowLayout.minimumInteritemSpacing = 10
        flowLayout.scrollDirection = .horizontal
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 0), collectionViewLayout: flowLayout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = .clear
        collectionView.register(NutritionAndHealthViewCell.classForCoder(), forCellWithReuseIdentifier: "NutritionAndHealthViewCell")
        collectionView.register(UICollectionReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerView")
        
        return collectionView
    }()

}

extension NutritionAndHealthViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let image: UIImage = info[UIImagePickerController.InfoKey.editedImage] as! UIImage
        imgBtn.setImage(image, for: .normal)
        selectImg = image
        picker.dismiss(animated: true)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true)
    }
    
    private func updateImage() {
        guard selectImg.size.width > 0 && selectImg.size.height > 0 else {
            ShowHUD(str: "请选择图片")
            return
        }
        
        HUD.flash(.labeledProgress(title: "", subtitle: "图片分析中..."), delay: 5.0)
        let data = selectImg.jpegData(compressionQuality: 0.4) ?? Data()
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyyMMddHHmmss"
        let dateString = formatter.string(from: Date())
        let fileName = "iOS-\(dateString).jpeg"
        
        let bearer = Defaults[\.bearer]
        let headers: HTTPHeaders = [
            "Authorization": bearer
        ]
        
        AF.upload(multipartFormData: { multipartFormData in
            
            multipartFormData.append(data, withName: "image", fileName: fileName, mimeType: "image/jpeg")
            
        }, to: "\(BASE_URL)/Check/health", method: .post, headers: headers)
        .uploadProgress { progress in
            print("---------\(progress.fractionCompleted)")
        }
        .response { resp in
            HUD.hide()
            switch resp.result {
            case let .success(data):
                guard data != nil else {
                    ShowHUD(str: "返回数据为空")
                    return
                }
                
                let json = JSON(data!)
                print(json)
                let model = json.dictionaryObject?.kj.model(QIDictBaseModel.self) ?? QIDictBaseModel()
                guard model.code == 1 else {
                    ShowHUD(str: model.msg)
                    return
                }
                self.model = model.data.kj.model(NutritionAndHealthModel.self)
                self.foodList = self.model.list
                self.collectionView.reloadData()
            case let .failure(err):
                print(err)
            }
        }
    }
    
    
}


extension NutritionAndHealthViewController: TabulationViewDataSource {
    
    
    private func addMianRongJianKangUI() {
        
        tabulationView.frame = CGRect(x: 15, y: sizeTextF.bottom + 60, width: SCREEN_WIDTH - 30, height: CGFloat(41 * rowCount))
        tabulationView.backgroundColor = MainColor
        tabulationView.register(TextTabulationViewCell.self, forCellReuseIdentifier: reuseIdentifier)
        tabulationView.dataSource = self
        scrollView.addSubview(tabulationView)
        
    }
    
    func generateData() {
        grids.removeAll()
        for row in 0..<rowCount {
            var rowGrids = [Grid]()
            for col in 0..<colCount {
                var text = ""
                if col == 0 {
                    text = leftTitleArr[row]
                } else if col == 1 {
                    text = centerTitleArr[row]
                } else if col == 2 {
                    text = rightTitleArr.count > row ? rightTitleArr[row] : ""
                } else if col == 3 {
                    text = percentageTitleArr.count > row ? "\(percentageTitleArr[row])%" : ""
                }
                let grid = Grid(content: text)
                rowGrids.append(grid)
            }
            grids.append(rowGrids)
        }
        tabulationView.reloadData()
    }
    
    func numberOfRows(in tabulationView: TabulationView) -> Int {
        return rowCount
    }
    
    func numberOfCols(in tabulationView: TabulationView) -> Int {
        return colCount
    }
    
    //列宽
    func tabulationView(_ tabulationView: TabulationView, lengthForCol col: Int) -> CGFloat {
        if col < 2 {
            return (SCREEN_WIDTH - 30) / 3 - 1
        } else {
            return (SCREEN_WIDTH - 30) / 6
        }
    }
    
    func tabulationView(_ tabulationView: TabulationView, cellForIndexPath indexPath: TabIndexPath) -> TabulationViewCell? {
        
        guard let cell = tabulationView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as? TextTabulationViewCell else {
            return nil
        }
        guard grids.count > indexPath.row else {
            return cell
        }
        let rowGrids = grids[indexPath.row]
        guard rowGrids.count > indexPath.col else {
            return cell
        }
        let grid = rowGrids[indexPath.col]
        cell.loadGrid(grid)
        return cell
    }
}

extension NutritionAndHealthViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 120, height: 70)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        foodList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NutritionAndHealthViewCell", for: indexPath) as! NutritionAndHealthViewCell
        cell.model = foodList[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = foodList[indexPath.row]
        getHealthConfirm(model: model)
//        titleL8.text = model.name
//        weightTextF.text = "100"
//        QINetworkManager.requestJson(urlStr: "/Check/healthConfirm", parameters: ["predicted_id": model.id]) { json in
//            print(json)
//            self.selectFoodID = json["id"].stringValue
//            self.setRightTitleArr(json: json)
//        }
    }
    
    /// 获取营养列表
    private func getHealthConfirm(model: FoodModel) {
        titleL8.text = model.name
        let arr = model.button_on_or_off.components(separatedBy: ",")
        if arr.count == 3 {
            weightTextF.text = arr[0] == "1" ? "100" : ""
            capacityTextF.text = arr[1] == "1" ? "100" : ""
//            sizeTextF.text = arr[2]
        }
        QINetworkManager.requestJson(urlStr: "/Check/healthConfirm", parameters: ["predicted_id": model.id]) { json in
            print(json)
            self.selectFoodID = json["id"].stringValue
            self.setRightTitleArr(json: json)
        }
    }
    
    private func setRightTitleArr(json: JSON) {
        self.rightTitleArr.removeAll()
//        self.rightTitleArr.append(json["energy"].stringValue)
//        self.rightTitleArr.append(json["protein"].stringValue)
//        self.rightTitleArr.append(json["carbohydrates"].stringValue)
//        self.rightTitleArr.append(json["fat"].stringValue)
//        self.rightTitleArr.append(json["dietary_fiber"].stringValue)
//        self.rightTitleArr.append(json["sugar"].stringValue)
//        self.rightTitleArr.append(json["saturated"].stringValue)
//        self.rightTitleArr.append(json["trans_fat"].stringValue)
//        self.rightTitleArr.append(json["cholesterol"].stringValue)
//        self.rightTitleArr.append(json["calcium"].stringValue)
//        self.rightTitleArr.append(json["copper"].stringValue)
//        self.rightTitleArr.append(json["iron"].stringValue)
//        self.rightTitleArr.append(json["magnesium"].stringValue)
//        self.rightTitleArr.append(json["manganese"].stringValue)
//        self.rightTitleArr.append(json["phosphorus"].stringValue)
//        self.rightTitleArr.append(json["potassium"].stringValue)
//        self.rightTitleArr.append(json["sodium"].stringValue)
//        self.rightTitleArr.append(json["iron"].stringValue)
//        self.rightTitleArr.append(json["vitamin_c"].stringValue)
        
//        self.rightTitleArr.append(json["energy_information"].stringValue)
//        self.rightTitleArr.append(json["protein_information"].stringValue)
//        self.rightTitleArr.append(json["carbohydrates_information"].stringValue)
//        self.rightTitleArr.append(json["fat_information"].stringValue)
//        self.rightTitleArr.append(json["dietary_fiber_information"].stringValue)
//        self.rightTitleArr.append(json["sugar_information"].stringValue)
//        self.rightTitleArr.append(json["saturated_information"].stringValue)
//        self.rightTitleArr.append(json["trans_fat_information"].stringValue)
//        self.rightTitleArr.append(json["cholesterol_information"].stringValue)
//        self.rightTitleArr.append(json["calcium_information"].stringValue)
//        self.rightTitleArr.append(json["copper_information"].stringValue)
//        self.rightTitleArr.append(json["iron_information"].stringValue)
//        self.rightTitleArr.append(json["magnesium_information"].stringValue)
//        self.rightTitleArr.append(json["manganese_information"].stringValue)
//        self.rightTitleArr.append(json["phosphorus_information"].stringValue)
//        self.rightTitleArr.append(json["potassium_information"].stringValue)
//        self.rightTitleArr.append(json["sodium_information"].stringValue)
//        self.rightTitleArr.append(json["zinc_information"].stringValue)
//        self.rightTitleArr.append(json["vitamin_c_information"].stringValue)
        
        
        self.percentageTitleArr.removeAll()
//        self.percentageTitleArr.append(json["energy_proportion"].stringValue)
//        self.percentageTitleArr.append(json["protein_proportion"].stringValue)
//        self.percentageTitleArr.append(json["carbohydrates_proportion"].stringValue)
//        self.percentageTitleArr.append(json["fat_proportion"].stringValue)
//        self.percentageTitleArr.append(json["dietary_fiber_proportion"].stringValue)
//        self.percentageTitleArr.append(json["sugar_proportion"].stringValue)
//        self.percentageTitleArr.append(json["saturated_proportion"].stringValue)
//        self.percentageTitleArr.append(json["trans_fat_proportion"].stringValue)
//        self.percentageTitleArr.append(json["cholesterol_proportion"].stringValue)
//        self.percentageTitleArr.append(json["calcium_proportion"].stringValue)
//        self.percentageTitleArr.append(json["copper_proportion"].stringValue)
//        self.percentageTitleArr.append(json["iron_proportion"].stringValue)
//        self.percentageTitleArr.append(json["magnesium_proportion"].stringValue)
//        self.percentageTitleArr.append(json["manganese_proportion"].stringValue)
//        self.percentageTitleArr.append(json["phosphorus_proportion"].stringValue)
//        self.percentageTitleArr.append(json["potassium_proportion"].stringValue)
//        self.percentageTitleArr.append(json["sodium_proportion"].stringValue)
//        self.percentageTitleArr.append(json["iron_proportion"].stringValue)
//        self.percentageTitleArr.append(json["vitamin_c_proportion"].stringValue)
        
        processingData(key: "energy", json: json)
        processingData(key: "protein", json: json)
        processingData(key: "carbohydrates", json: json)
        processingData(key: "fat", json: json)
        processingData(key: "dietary_fiber", json: json)
        processingData(key: "sugar", json: json)
        processingData(key: "saturated", json: json)
        processingData(key: "trans_fat", json: json)
        processingData(key: "cholesterol", json: json)
        processingData(key: "calcium", json: json)
        processingData(key: "copper", json: json)
        processingData(key: "iron", json: json)
        processingData(key: "magnesium", json: json)
        processingData(key: "manganese", json: json)
        processingData(key: "phosphorus", json: json)
        processingData(key: "potassium", json: json)
        processingData(key: "sodium", json: json)
        processingData(key: "Zinc", json: json)
        processingData(key: "vitamin_c", json: json)
        
        self.generateData()
    }
    
    private func processingData(key: String, json: JSON) {
        let information = json["\(key)_information"].stringValue
        if information == "-1" {
            self.rightTitleArr.append("-1")
        } else {
            self.rightTitleArr.append(json[key].stringValue)
        }
        self.percentageTitleArr.append(json["\(key)_proportion"].stringValue)
    }
    
}


class NutritionAndHealthViewCell: UICollectionViewCell {
    
    private var nameL = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addUI()
    }
    
    private func addUI() {
        nameL = UILabel().then({
            $0.frame = CGRect(x: 0, y: 0, width: self.width, height: 30)
            $0.text = ""
            $0.numberOfLines = 2
            $0.textAlignment = .center
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 12)
        })
        self.addSubview(nameL)
        
        let confirmL = UILabel().then({
            $0.frame = CGRect(x: self.width / 2 - 33, y: nameL.bottom + 4, width: 66, height: 34)
            $0.backgroundColor = MainColor
            $0.text = "确定"
            $0.textAlignment = .center
            $0.textColor = .white
            $0.font = SYSFONT(ofSize: 14)
            $0.addRoundedCorners(withRadius: 5)
        })
        self.addSubview(confirmL)
    }
    
    var model = FoodModel() {
        didSet {
            nameL.text = "\(model.name)\n 12%"
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
